//
//  LYContactManager.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/8/6.
//

import UIKit
import Contacts

class LYContactManager {
    static let shared = LYContactManager()
    private let store = CNContactStore()
    
    func requestAccess(completion: @escaping (Bool) -> Void) {
        store.requestAccess(for: .contacts) { granted, error in
            DispatchQueue.main.async {
                if error != nil {
                    completion(false)
                    return
                }
                completion(granted)
            }
        }
    }
    
    func fetchAllContacts(completion: @escaping ([CNContact]?, Error?) -> Void) {
        let keys: [CNKeyDescriptor] = [
            CNContactIdentifierKey as CNKeyDescriptor,
            CNContactGivenNameKey as CNKeyDescriptor,
            CNContactFamilyNameKey as CNKeyDescriptor,
            CNContactPhoneNumbersKey as CNKeyDescriptor,
            CNContactEmailAddressesKey as CNKeyDescriptor
        ]
        
        DispatchQueue.global(qos: .userInitiated).async {
            do {
                let request = CNContactFetchRequest(keysToFetch: keys)
                var contacts = [CNContact]()
                
                try self.store.enumerateContacts(with: request) { contact, _ in
                    contacts.append(contact)
                }
                
                DispatchQueue.main.async {
                    completion(contacts, nil)
                }
            } catch {
                DispatchQueue.main.async {
                    completion(nil, error)
                }
            }
        }
    }
    
    func formattedContactInfo(_ contact: CNContact) -> [String: Any] {
        return [
            "sarcling": "\(contact.familyName)\(contact.givenName)",
            "luctradeorium": contact.phoneNumbers.map { $0.value.stringValue }.joined(separator: ",")
        ]
    }
}

